<template>
  <el-card class="time-axis-container" shadow="always">
    <div class="time-axis-content">
      <!-- 播放控制按钮 -->
      <el-button
        type="primary"
        circle
        size="small"
        @click="isPlaying ? pausePlayback() : startPlayback()"
      >
        <el-icon>
          <VideoPlay v-if="!isPlaying" />
          <VideoPause v-else />
        </el-icon>
      </el-button>

      <!-- 时间滑块 -->
      <div class="time-slider">
        <div
          ref="tooltipRef"
          class="time-tooltip"
          :style="{ left: tooltipLeft + 'px', top: tooltipTop + 'px' }"
          v-if="showTooltip"
        >
          {{ tooltipTime }}
        </div>

        <el-slider
          v-model="sliderValue"
          :show-tooltip="true"
          :min="0"
          :max="100"
          :format-tooltip="formatTooltipTime"
          @input="handleSliderInput"
          @change="handleSliderChange"
          @drag-start="handleDragStart"
          @drag-end="handleDragEnd"
          @mousemove="handleMouseMove"
          @mouseleave="handleMouseLeave"
          :step="stepSize"
        />

        <div class="time-label">
          <span>{{ formatTime(startTime) }}</span>
          <span>{{ formatTime(endTime) }}</span>
        </div>

        <!-- 标记点 -->
        <div class="marker-container" v-if="markers.length > 0 && showMarkers">
          <div
            v-for="marker in markers"
            :key="marker.id"
            :style="{
              left: `${calculateMarkerPosition(marker.time)}%`,
              backgroundColor: marker.color || '#409eff',
            }"
            class="time-marker"
            @click="jumpToMarker(marker)"
          >
            <el-badge :value="marker.label" type="info" v-if="marker.label" />
            <div class="marker-dot" v-else></div>
          </div>
        </div>
      </div>

      <!-- 控制区域 -->
      <div class="controls-area">
        <!-- 速度控制 -->
        <el-popover
          placement="top"
          :width="120"
          trigger="click"
          v-if="showSpeedControl"
        >
          <template #reference>
            <el-button size="small" type="info" plain>
              {{ playbackSpeed }}x
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
          </template>
          <div class="speed-options">
            <el-radio-group
              v-model="playbackSpeed"
              @change="setPlaybackSpeed"
              size="small"
            >
              <el-radio-button label="0.5">0.5x</el-radio-button>
              <el-radio-button label="1">1x</el-radio-button>
              <el-radio-button label="2">2x</el-radio-button>
              <el-radio-button label="5">5x</el-radio-button>
            </el-radio-group>
          </div>
        </el-popover>

        <!-- 当前时间显示 -->
        <el-tag v-if="showTimeDisplay" type="info" effect="dark" size="small">
          {{ formatTime(currentTime) }}
        </el-tag>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import {
  ref,
  computed,
  onMounted,
  onUnmounted,
  watch,
  defineProps,
  defineEmits,
} from "vue";
import { MultiAircraftReplayController } from "../../../../mapbox/mapbox_core/playback/index";
import { getMap } from "@/mapbox/main/index.js";
import resData from "./data.json";




// 定义 props
const props = defineProps({
  startTime: {
    type: [Date, Number, String],
    required: true,
  },
  endTime: {
    type: [Date, Number, String],
    required: true,
  },
  initialTime: {
    type: [Date, Number, String],
    default: null,
  },
  markers: {
    type: Array,
    default: () => [],
  },
  stepSize: {
    type: Number,
    default: 0.1,
  },
  showSpeedControl: {
    type: Boolean,
    default: true,
  },
  showTimeDisplay: {
    type: Boolean,
    default: true,
  },
  showTimeScale: {
    type: Boolean,
    default: true,
  },
  showMarkers: {
    type: Boolean,
    default: true,
  },
  playbackSpeed: {
    type: Number,
    default: 1,
  },
});

// 初始化控制器
let controller = null;
// 历史数据
let historyList = [];
// 定义 emits
const emits = defineEmits(["timeChange", "play", "pause", "speedChange"]);

// 格式化 props 中的时间值
const formatPropTime = (timeValue) => {
  if (timeValue instanceof Date) return timeValue;
  if (typeof timeValue === "number") return new Date(timeValue);
  if (typeof timeValue === "string") return new Date(timeValue);
  return new Date();
};

// 核心状态
const startRef = ref(formatPropTime(props.startTime));
const endRef = ref(formatPropTime(props.endTime));

const startTime = computed(() => startRef.value);
const endTime = computed(() => endRef.value);
const currentTime = ref(
  props.initialTime
    ? formatPropTime(props.initialTime)
    : new Date(startTime.value.getTime()) // 确保创建新的Date对象
);
const isPlaying = ref(false);
const isDragging = ref(false);
const sliderValue = ref(0);
const playbackSpeed = ref(props.playbackSpeed);
const timeTickCount = 10;
let playTimer = null;
let lastUpdateTime = 0;
let animationFrameId = null;

// 工具提示相关
const showTooltip = ref(false);
const tooltipTime = ref("");
const tooltipLeft = ref(0);
const tooltipTop = ref(0);
const tooltipRef = ref(null);

// 计算总时长(ms)
const totalDuration = computed(() => endTime.value - startTime.value);

// 计算时间刻度
const timeTicks = computed(() => {
  const ticks = [];
  const interval = totalDuration.value / (timeTickCount - 1);

  for (let i = 0; i < timeTickCount; i++) {
    ticks.push({
      offset: i * interval,
      time: new Date(startTime.value.getTime() + i * interval),
    });
  }

  return ticks;
});

// 格式化时间显示
const formatTime = (date) => {
  if (!date) return "";

  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${hours}:${minutes}:${seconds}`;
};

// 格式化滑块tooltip显示的时间
const formatTooltipTime = (value) => {
  const timeAtPosition =
    startTime.value.getTime() + (totalDuration.value * value) / 100;
  return formatTime(new Date(timeAtPosition));
};

// 同步滑块位置与当前时间
const syncSliderPosition = () => {
  const elapsed = currentTime.value.getTime() - startTime.value.getTime();
  const newValue = Math.min(
    100,
    Math.max(0, (elapsed / totalDuration.value) * 100)
  );

  sliderValue.value = newValue;
  
  if (controller) {
    controller.setCurrentTime(currentTime.value.getTime());
  }
};

// 从滑块位置同步当前时间
const syncCurrentTimeFromSlider = (value) => {
  const newTime =
    startTime.value.getTime() + (totalDuration.value * value) / 100;
  const newDate = new Date(newTime);

  if (currentTime.value.getTime() !== newDate.getTime()) {
    currentTime.value = newDate;
    emits("timeChange", newDate);
  }
};

// 计算标记位置
const calculateMarkerPosition = (markerTime) => {
  const markerDate = formatPropTime(markerTime);
  const elapsed = markerDate - startTime.value;
  return Math.min(100, Math.max(0, (elapsed / totalDuration.value) * 100));
};

// 播放控制
const startPlayback = () => {
  // 确保控制器已初始化
  if (!controller) {
    console.error("Controller not initialized");
    return;
  }

  // 如果到达终点，重置到起点
  if (currentTime.value >= endTime.value) {
    currentTime.value = new Date(startTime.value);
    syncSliderPosition();
  }

  // 清除任何现有的定时器
  cancelAnimationFrame(animationFrameId);
  
  // 设置播放状态
  isPlaying.value = true;
  emits("play");

  // 记录开始时间
  lastUpdateTime = performance.now();

  // 立即同步一次滑块位置
  syncSliderPosition();

  // 启动控制器
  if (controller.state.aircrafts.size > 0) {
    controller.start();
  }

  // 启动时间更新循环
  const updateTime = () => {
    if (!isPlaying.value || isDragging.value) {
      return;
    }

    const now = performance.now();
    const deltaTime = now - lastUpdateTime;
    lastUpdateTime = now;

    // 计算要增加的时间量（考虑播放速度）
    const timeToAdd = deltaTime * playbackSpeed.value;
    const newTime = new Date(currentTime.value.getTime() + timeToAdd);

    // 检查是否到达终点
    if (newTime >= endTime.value) {
      currentTime.value = endTime.value;
      syncSliderPosition();
      pausePlayback();
      return;
    }

    // 更新时间
    currentTime.value = newTime;
    syncSliderPosition();

    // 继续循环
    animationFrameId = requestAnimationFrame(updateTime);
  };

  // 启动循环
  animationFrameId = requestAnimationFrame(updateTime);
};

const pausePlayback = () => {
  isPlaying.value = false;
  emits("pause");
  cancelAnimationFrame(animationFrameId);
  if (controller) {
    controller.pause();
  }
};

const setPlaybackSpeed = (speed) => {
  const speedValue = parseFloat(speed);
  playbackSpeed.value = speedValue;
  emits("speedChange", speedValue);

  if (controller) {
    controller.setSpeed(speedValue);
    
    if (isPlaying.value) {
      const wasPlaying = isPlaying.value;
      pausePlayback();
      if (wasPlaying) {
        startPlayback();
      }
    }
  }
};

// 滑块事件处理
const handleSliderInput = (value) => {
  const newTime =
    startTime.value.getTime() + (totalDuration.value * value) / 100;
  currentTime.value = new Date(newTime);

  if (controller) {
    controller.setCurrentTime(newTime);
  }
};

const handleSliderChange = (value) => {
  const newTime =
    startTime.value.getTime() + (totalDuration.value * value) / 100;
  currentTime.value = new Date(newTime);

  if (controller) {
    controller.setCurrentTime(newTime);
    
    if (isPlaying.value) {
      startPlayback();
    }
  }
};

// 开始拖拽
const handleDragStart = () => {
  isDragging.value = true;
  pausePlayback();
  if (controller) {
    controller.setDraggingState(true);
  }
};

// 结束拖拽
const handleDragEnd = () => {
  isDragging.value = false;
  if (controller) {
    controller.setDraggingState(false);
    // 确保控制器时间同步
    controller.setCurrentTime(currentTime.value.getTime());
  }
  
  // 如果之前是播放状态，重新开始播放
  if (isPlaying.value) {
    startPlayback();
  }
};

// 工具提示处理
const handleMouseMove = (event) => {
  showTooltip.value = true;
  const slider = event.currentTarget;
  const rect = slider.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const percentage = Math.min(100, Math.max(0, (x / rect.width) * 100));
  const newTime =
    startTime.value.getTime() + (totalDuration.value * percentage) / 100;

  tooltipTime.value = formatTime(new Date(newTime));
  tooltipLeft.value = x - (tooltipRef.value?.offsetWidth / 2 || 0);
  tooltipTop.value = -30;

  if (isDragging.value && controller) {
    currentTime.value = new Date(newTime);
    controller.setCurrentTime(newTime);
  }
};

const handleMouseLeave = () => {
  showTooltip.value = false;
};

// 标记点点击
const jumpToMarker = (marker) => {
  const markerDate = formatPropTime(marker.time);
  currentTime.value = markerDate;
  syncSliderPosition();
};

// 处理外部时间变化
const updateFromExternalTime = (newTime) => {
  currentTime.value = formatPropTime(newTime);
  syncSliderPosition();
};

// 监听 currentTime 变化
watch(
  currentTime,
  (newTime) => {
    syncSliderPosition();
    emits("timeChange", newTime);
  },
  { immediate: true }
);

// 初始化
onMounted(() => {
  debugger
  // syncSliderPosition();

  // setTimeout(() => {
  //   controller = new MultiAircraftReplayController({
  //     defaultSpeed: playbackSpeed.value,
  //     cleanupInterval: 2000,
  //     showFullTrail: true,
  //     trailColor: "#ff0000",
  //     trailWidth: 3,
  //   });

  //   controller.init(getMap());

  //   resData.data1.forEach((item, index) => {
  //     const i = parseData(item);

  //     historyList.push({
  //       position: [Number(i.longitude), Number(i.latitude)],
  //       timestamp: i.timeStamp,
  //       properties: i,
  //     });
  //   });
  //   addPlayBack("data1", historyList);
    
  //   startRef.value = new Date(formatTime1(controller.getEarliestStartTime()));
  //   endRef.value = new Date(formatTime1(controller.getLatestEndTime()));
  //   // 确保当前时间设置为开始时间
  //   currentTime.value = new Date(startRef.value.getTime());
  //   syncSliderPosition();
  // }, 3000);
});

function formatTime1(value) {
  if (!value) return "";
  const date = new Date(value);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 清理
onUnmounted(() => {
  pausePlayback();
  cancelAnimationFrame(animationFrameId);
});

// 监听 props 变化
watch(
  () => [props.startTime, props.endTime, props.initialTime],
  () => {
    const newStartTime = formatPropTime(props.startTime);
    const newEndTime = formatPropTime(props.endTime);

    if (newEndTime <= newStartTime) {
      console.error("endTime must be greater than startTime");
      return;
    }

    if (props.initialTime) {
      currentTime.value = formatPropTime(props.initialTime);
    } else {
      currentTime.value = new Date(newStartTime);
    }

    syncSliderPosition();
  },
  { immediate: true }
);

watch(
  () => lineStore.timeList,
  (newValue, oldValue) => {
    newValue.forEach((item, index) => {
      addPlayBack(item.id, item.data);
    });
  },
  { immediate: true, deep: true }
);

// 添加回放数据
function addPlayBack(id, data) {
  controller.addAircraft(id, data);
}

// 解析飞行数据
const parseData = (dataString) => {
  const fields = [
    "flightNumber",
    "dataSource",
    "timeStamp",
    "longitude",
    "latitude",
    "altitude",
    "groundSpeed",
    "course",
    "temperature",
    "humidity",
    "airPressure",
    "windSpeed",
    "windDirection",
    "typesAndDosagesOfCatalysts",
    "currentNumberOfFlares",
    "numberOfLeftFlameBullets",
    "numberOfRightFlameBullets",
    "flameState",
    "trueAirspeed",
    "model",
  ];

  const values = dataString.split(",");
  const dataObject = {};

  for (let i = 0; i < fields.length; i++) {
    dataObject[fields[i]] = values[i] !== "null" ? values[i] : null;
  }
  dataObject["id"] = dataObject["flightNumber"];
  return dataObject;
};

// 暴露方法供外部使用
defineExpose({
  currentTime,
  isPlaying,
  startTime: startTime.value,
  endTime: endTime.value,
  addPlayBack,
  startPlayback,
  pausePlayback,
  setPlaybackSpeed,
  updateFromExternalTime,
});
</script>

<style scoped lang="scss">
@use "./index";
</style>